package logic

import (
	"context"
	"encoding/json"
	"time"
	"transaction/moder/cache"
	"transaction/moder/mysql"

	"transaction/tranrpc/internal/svc"
	"transaction/tranrpc/tranrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserListLogic) UserList(in *tranrpc.UserListRequest) (*tranrpc.UserListResponse, error) {
	// todo: add your logic here and delete this line

	var user []mysql.User
	result, _ := cache.Rdb.Get(l.ctx, "userlist").Result()
	if result == "" {
		mysql.DB.Scopes(mysql.Paginate(int(in.Page), int(in.Size))).Find(&user)
		marshal, _ := json.Marshal(user)
		cache.Rdb.Set(l.ctx, "userlist", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	var userList []*tranrpc.UserList
	for _, users := range user {
		list := tranrpc.UserList{
			Username: users.Username,
			Password: users.Password,
			UserId:   int64(users.ID),
		}
		userList = append(userList, &list)
	}
	return &tranrpc.UserListResponse{
		List: userList,
	}, nil
}
